package com.google.mlkit.samples.nl.translate;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class AssetCopyHelper {
    private static final String TAG = "AssetCopyHelper";

    /**
     * 复制 assets 中的 ML Kit 翻译模型到内部数据目录
     */
    public static boolean copyTranslateModels(Context context) {

        try {
            File targetDir = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                targetDir = new File(context.getDataDir(), "no_backup" + File.separator + "com.google.mlkit.translate.models");
            }
            if(targetDir == null)
                return false;
            copyAssetsToDirectory(context, "com.google.mlkit.translate.models", targetDir);
            Log.d(TAG, "ML Kit translation models copied successfully");
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Failed to copy ML Kit models", e);
        }
        return false;
    }
    /**
     * 递归复制 assets 文件夹到目标目录
     */
    private static void copyAssetsToDirectory(Context context, String assetsPath, File targetDir) {
        AssetManager assetManager = context.getAssets();

        // 创建目标目录（如果不存在）
        if (!targetDir.exists()) {
            if (!targetDir.mkdirs()) {
                Log.e(TAG, "Failed to create target directory: " + targetDir.getAbsolutePath());
                return;
            }
        }

        try {
            // 获取 assets 中的文件/文件夹列表
            String[] items = assetManager.list(assetsPath);
            if (items == null || items.length == 0) {
                Log.w(TAG, "No items found in assets: " + assetsPath);
                return;
            }

            for (String itemName : items) {
                String assetItemPath = assetsPath + File.separator + itemName;
                File targetItem = new File(targetDir, itemName);

                // 检查是否是目录
                try {
                    String[] subItems = assetManager.list(assetItemPath);
                    if (subItems != null && subItems.length > 0) {
                        // 如果是目录，递归复制
                        copyAssetsToDirectory(context, assetItemPath, targetItem);
                    } else {
                        // 如果是文件，复制文件（跳过已存在的）
                        if (!targetItem.exists()) {
                            copyFile(assetManager, assetItemPath, targetItem);
                        } else {
//                            Log.d(TAG, "Skipping existing file: " + targetItem.getAbsolutePath());
                        }
                    }
                } catch (Exception e) {
                    // 如果 list() 抛出异常，说明是文件
                    if (!targetItem.exists()) {
                        copyFile(assetManager, assetItemPath, targetItem);
                    } else {
//                        Log.d(TAG, "Skipping existing file: " + targetItem.getAbsolutePath());
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error copying assets folder", e);
        }
    }

    /**
     * 复制单个文件
     */
    private static void copyFile(AssetManager assetManager, String assetPath, File targetFile) {
        try (InputStream in = assetManager.open(assetPath);
             OutputStream out = new FileOutputStream(targetFile)) {

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }

            Log.d(TAG, "Copied file: " + targetFile.getName());
        } catch (Exception e) {
            Log.e(TAG, "Failed to copy file: " + assetPath, e);

            // 删除可能已创建但未完整复制的文件
            if (targetFile.exists()) {
                if (!targetFile.delete()) {
                    Log.w(TAG, "Failed to delete incomplete file: " + targetFile.getName());
                }
            }
        }
    }
}